﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class PlaceholderTextBox : TextBox
    {
        private string placeholderText;

        public string PlaceholderText
        {
            get { return placeholderText; }
            set
            {
                placeholderText = value;
                // 当文本框内容为空时显示占位符
                if (string.IsNullOrEmpty(this.Text))
                {
                    this.Text = placeholderText;
                    this.ForeColor = Color.Gray; // 占位符文本颜色
                }
            }
        }
        public PlaceholderTextBox()
        {
            InitializeComponent();
            // 设置默认的占位符文本
            this.PlaceholderText = "";
            this.ForeColor = Color.Gray; // 默认占位符文本颜色

            // 当文本框得到焦点时，如果内容是占位符，则清空
            this.Enter += (s, e) =>
            {
                if (this.Text == placeholderText)
                {
                    this.Text = "";
                    this.ForeColor = SystemColors.WindowText; // 恢复默认文本颜色
                }
            };

            // 当文本框失去焦点时，如果内容为空，则显示占位符
            this.Leave += (s, e) =>
            {
                if (string.IsNullOrEmpty(this.Text))
                {
                    this.Text = placeholderText;
                    this.ForeColor = Color.Gray; // 恢复占位符文本颜色
                }
            };
        }
    }
}
